#include "airkiss.h"

#include <string.h>
#include <stdint.h>

#if 1//def Q_DEBUG
#include <qlogging.h>

#define AKLOG_D qDebug
#else
#define AKLOG_D(...)
#endif

#define AKSTATE_WFG    0
#define AKSTATE_WFM    1

typedef struct
{
    char ssid[33];
    char pwd[25];
    uint16_t code[8];
    uint8_t seq;
    uint8_t baselen;
    uint8_t pos;
    char state;
}akloc_context_t;

static int ak_waitfor_guide(akloc_context_t* lc, uint8_t *f, uint16_t len)
{
    int ret = AIRKISS_STATUS_CONTINUE;

    if (lc->pos < 4)
    {
        if ((lc->pos != 0) && ((len - lc->code[lc->pos - 1]) != 1))
        {
            lc->pos = 0;
        }

        lc->code[lc->pos] = len;
        lc->pos ++;
    }

    if (lc->pos == 4)
    {
        if ((lc->code[1] - lc->code[0] == 1) &&
            (lc->code[2] - lc->code[0] == 2) &&
            (lc->code[3] - lc->code[0] == 3))
        {
            lc->baselen = lc->code[0] - 1;
            lc->state = AKSTATE_WFM;

            AKLOG_D("guide baselen %d\n", lc->baselen);
        }

        lc->pos = 0;
    }

    return ret;
}

static int ak_waitfor_magic(akloc_context_t* lc, uint8_t *f, int len)
{
    return 0;
}

const char* airkiss_version(void)
{
    return "open:v1.0.0";
}

int airkiss_init(airkiss_context_t* c, const airkiss_config_t* config)
{
    memset(c, 0, sizeof(*c));

    return 0;
}

int airkiss_recv(airkiss_context_t* c, const void* frame, unsigned short length)
{
    int ret = 0;
    akloc_context_t* lc = (akloc_context_t*)c;
    unsigned char *f = (unsigned char *)frame;

    switch (lc->state)
    {
    case AKSTATE_WFG:
    {
        ak_waitfor_guide(lc, f, length);
    }break;
    case AKSTATE_WFM:
    {
        ak_waitfor_magic(lc, f, length);
    }break;
    }

    return ret;
}
